<?

class LawAdminAction extends Action {
  function _initialize() {
    header('content-Type=text/html;charset=utf-8');
    if (ACTION_NAME != "login") {
      $this->checkLogin();
    }
  }

  public function checkLogin() {
    if ($_SESSION['user_name'] != "ehs" && $_SESSION['password'] != "ehscn") {
      $this->redirect('LawAdmin/login','',2,'您还没有登陆，请重新登陆，页面跳转中~');
    }
  }

  public function index() {
    $this->display();

  }

  /*  登陆  */
  public function login() {
    if ($_POST['user_name'] == "ehs" && $_POST['password'] == "ehscn") {
      $_SESSION['user_name'] = "ehs";
      $_SESSION['password'] = "ehscn";
      $this->redirect('LawAdmin/index', '', 2, "登陆成功，页面跳转中~~~");
    }else {
      $this->display();
    }
  }

  /*  法规列表   */
  /*
  public function lawList0() {
    $m = M();
    $select = "select t1.id,t1.ltitle as title,t1.luser as issue,t1.ldate_pub as date_pub,t1.zy_id,t2.title as zy_title,t1.hy_id,t3.title as hy_title,t1.dq_id,t4.title as dq_title,t1.lawtype_id as lawtype_id,t5.Laytype_name as lawtype_title ";
    $selectCount = "select count(*) ";
    $from = " from a_law t1
        left join a_zy t2 on (t1.zy_id = t2.id)
        left join a_hy t3 on (t1.hy_id = t3.id)
        left join a_region t4 on (t1.dq_id = t4.id)
        left join a_lawtype t5 on (t1.lawtype_id=t5.id)
        where 1 ";
    $order = " order by date_pub desc";
    $where = "";
    if ($_POST['ltitle'] && $_POST["ltitle"] != "") $where .= " and ltitle like '%".$_POST['ltitle']."%'";
    if ($_POST['type_id'] && $_POST["type_id"] != "") $where .= " and ".$_POST['type_id']." in (".$_POST['type_id_value'].")";
    $count = $m->query($selectCount.$from.$where);
    $count = $count[0]["count(*)"];
    import("@.ORG.Page"); //导入分页类
    $records = 50;//每页多少条记录
    
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $limit = " limit ".$p->firstRow.",".$p->listRows;
    $sql = $select.$from.$where;
    $list = $m->query($sql.$order.$limit);
    $this->assign("count", $count);
    $this->assign("resultList", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->display("law-list");
  } */

  /*  用Ajax改写  */
  public function lawList() {
    $this->display("law-list");
  }

  public function search() {
	$time_s=time(); 
    $m = M();
    $select = "select t1.id,ifnull(t1.ltitle,'') as title,ifnull(t1.luser,'') as issue,t1.ldate_pub as date_pub,ldate_job,ldate_stop,
      t1.zy_id,ifnull(t2.title,'') as zy_title,t1.hy_id,ifnull(t3.title,'') as hy_title,
      t1.dq_id,ifnull(t4.title,'') as dq_title,t1.lawtype_id as lawtype_id,ifnull(t5.Laytype_name,'') as lawtype_title,app_type,status ";
    $selectCount = "select count(*) ";
    $from = " from a_law t1
        left join a_zy t2 on (t1.zy_id = t2.id)
        left join a_hy t3 on (t1.hy_id = t3.id)
        left join a_region t4 on (t1.dq_id = t4.id)
        left join a_lawtype t5 on (t1.lawtype_id=t5.id)
        where 1 ";
    $order = " order by id ASC ";
    $where = "";
    if ($_POST['ltitle'] && $_POST["ltitle"] != "") $where .= " and ltitle like '%".$_POST['ltitle']."%'";
    if ($_POST['type_id'] && $_POST["type_id"] != "") {
	  if($_POST['type_id'] == 'app')
	    $_POST['type_id'] = 'app_type';
	  $where .= " and ".$_POST['type_id']." in (".$_POST['type_id_value'].")";
	}
	if ($_POST['isNew']==1) $where .= " and status>0";
	if(!empty($_POST['status'])){
		$status=0;
		if($_POST['isNew']!='' && $_POST['isNew']==0)//全部旧数据
	   	 	$status=$_POST['status']==1?0:$_POST['status'];
	    else
			$status=$_POST['status'];
		$where .= " and status={$status}";//
	}
	
	  
    $sql = $selectCount.$from.$where;
    $count = $m->query($sql);
	//alert($_POST);
	//alert($m->getLastSQL());
    $count = $count[0]["count(*)"];
    $size = 18;
    $list = array();
    if ($count > 0) {
      $page = $_POST['page']>0?$_POST['page']:1;
      $sql = $select.$from.$where.$order." limit ".($page-1)*$size.",".$size;
      $list = $m->query($sql);
	  //alert($m->getLastSQL());
    } else $page = 0;
	//alert($m->getLastSQL());
	$m=M('AHy');
	$hy=$m->field('id,title,did')->order('DID ASC,title ASC')->select();
	$hy_select=array();
	foreach($hy as $h){
		if($h['did']==0){
		  $hy_select[$h['id']]['title']=$h['title'];
		 }
		else{
		  $hy_select[$h['did']]['kids'][]=$h;		
		}
	}
	//alert($m->getLastSQL());
	$m=M('AZy');
	$zy=$m->field('id,title,did')->where('did>0')->order('title ASC')->select();
	$zy_select=array();
	//$first_ids=array();
	//$second_ids=array();
	//$select=array();
	foreach($zy as $z){
		if($z['did']<8){
		  $zy_select[$z['id']]['title']=$z['title'];
		 }
		else{
		  $zy_select[$z['did']]['kids'][]=$z;		
		}
	}
	//dump($zy_select);
	
	$m=M('ALawtype');
	$type=$m->field('id,laytype_name as name')->order('px ASC')->select();
	
	$m=M('ARegion');
	$region=$m->field('id,title,did')->order('did ASC,px DESC')->select();
	$reg_select=array();
	foreach($region as $reg){
		if($reg['did']==0){
			$reg_select[$reg['id']]['parent']=$reg;
		}
		else{
		    $reg_select[$reg['did']]['kids'][]=$reg;
		}
	}
	//dump($reg_select);exit();
	$m=M('ALawApptype');
	$appType=$m->field('id,name')->order('sort ASC')->select();	
	
	$time_end=time();
	$time_gap=$time_s-$time_end;
	//alert('使用'.$time_gap);
	
	$rt['hy'] = $hy_select;
	$rt['zy_select'] = $zy_select;
	$rt['type'] = $type;
	$rt['region'] = $reg_select;
	$rt['appType'] = $appType;
    $rt['list'] = $list;
    $rt['page'] = $page;
    $rt['count'] = $count;
    $rt['size'] = $size;
    $this->ajaxReturn($rt,"成功",1);
  }

  /*  新增法规  */
  public function insert() {
    if ($_POST) {
	  if(empty($_POST['id'])){	//增加记录
	    $filePath = '';//dump($_FILES['file']);exit();
		$fileSize = '0';	
	    if(!empty($_FILES['file']['name'])){
		   $info =  $this->_doUpload();//$upload->getUploadFileInfo();
		   $filePath = $info[0]['savepath'].'/'.$info[0]['savename'];
		   $fileSize = $info[0]['size'];
		}
        $m = M();
        $p = $_POST;
		$p["ldate_job"] = empty($p["ldate_job"])? '0000-00-00 00:00:00':$p["ldate_job"];
		$p["ldate_pub"] = empty($p["ldate_pub"])? '0000-00-00 00:00:00':$p["ldate_pub"];
		$p["ldate_stop"] = empty($p["ldate_stop"])? '0000-00-00 00:00:00':$p["ldate_stop"];
        $sql = "insert into a_law (ltitle,lnumber,luser,dq_id,zy_id,hy_id,lawtype_id,ldate_pub,ldate_job,ldate_stop,lcontent,file_url,file_size)
        values ('".$p['ltitle']."','".$p["lnumber"]."','".$p["luser"]."','".$p["dq_id"]."','".$p["zy_id"]."','".$p["hy_id"]."','".$p["lawtype_id"]."','".$p["ldate_pub"]."','".$p["ldate_job"]."','".$p["ldate_stop"]."','".$p["lcontent"]."','".$filePath."','".$fileSize."')";
        $rt = $m->query($sql);
        if (is_array($rt)) {
		   $this->assign('jumpUrl',__URL__.'/insert');
		   $this->success("添加成功，页面跳转中~~~");
		}
        else $this->error($m->getError());
	  }else{//修改记录
	     $data=$_POST;
	     if(!empty($_FILES['file']['name'])){
		   $info =  $this->_doUpload();//$upload->getUploadFileInfo();
		   //删除原附件
		   /*$m = M('ALaw');
		   $item= $m->find($data['id']);
		   if(!empty($item['file_url'])){
             $url = str_replace("m_bz", "/mod_bz", $item["file_url"]);
             $url = str_replace("bz_complete", "bz_complete/", $url);
             if(strpos($url,'attachment') !== false){
	           $url = '/main/'.$url; 
             }
			 alert($url);
			 if(file_exists($url))
			   unlink($fName);
           }*/
		   $data['file_url'] = $info[0]['savepath'].'/'.$info[0]['savename'];
		   $data['file_size'] = $info[0]['size'];
		}
		 $m=M('ALaw');
	     $m->save($data); 
		 $jumpUrl=__URL__.'/lawList';
		 $this->assign('jumpUrl',$jumpUrl);
		 $this->success('修改成功');
	  }
    }else {
      $m = M();
      $sql = "select * from a_lawtype";
      $lawType = $m->query($sql);
	  
	  $id=empty($_GET['id'])?0:$_GET['id'];
	  $m=M('ALaw');
	  $item=$m->find($id);
	  if(!empty($item['file_url'])){
       $url = str_replace("m_bz", "/mod_bz", $item["file_url"]);
       $url = str_replace("bz_complete", "bz_complete/", $url);
       if(strpos($url,'attachment') !== false){
	     $url = '/main/'.$url; 
       }
	   $item['file_url']=$url;
      }
	  //dump($item);
	  //echo $item['lcontent'];
	  //$item['lcontent']=htmlspecialchars(str_replace(array("\r\n","\n"),array('',''),$item['lcontent']));
	 //echo $item['lcontent'];
      //$zhr = $this->_getHZRList(array('a_zy','a_hy','a_region'));
	  $zhr = $this->_getHZRList(array('a_zy','a_hy','a_region'));
      $this->assign("lawType", $lawType);
	  $this->assign("item", $item);
      $this->assign("zhr",$zhr);
      $this->display();
    }
  }
  
  
  
  //修改法律
  public function editAjax(){
     /*foreach($_POST['ltitle'] as &$title){
	   //$title=mb_convert_encoding($title,'utf-8','gb2312'); 
	   iconv("UTF-8","gb2312",$title);
	 }*/
     //alert($_POST); 
	 //$this->ajaxReturn('1'); 
	 //$aa=$this->unicode_decode('\u5173\u4e8e\u4e09\u805a\u6c30\u80fa\u5728\u98df\u54c1\u4e2d\u7684\u9650\u91cf\u503c\u7684\u516c\u544a');
	 //alert($aa);exit();
	 $m=M('ALaw');
	 foreach($_POST['ids'] as $k=>$id){
	   $data=array();
	   $data['id']=(int)$id;
	   $data['luser']=$_POST['luser'][$k];//$_POST['luser'][$k];
	   //$this->unicode_decode($_POST['luser'][$k]);//mb_convert_encoding($_POST['luser'][$k],'utf-8','gb2312');//urldecode($_POST['luser'][$k]);
	   $data['hy_id']=$_POST['hy_id'][$k];
	   $data['zy_id']=$_POST['zy_id'][$k];
	   $data['dq_id']=$_POST['dq_id'][$k];
	   $data['ldate_pub']=$_POST['ldate_pub'][$k];
	   $data['ldate_job']=$_POST['ldate_job'][$k];
	   $data['ldate_stop']=$_POST['ldate_stop'][$k];
	   $data['lawtype_id']=$_POST['lawtype_id'][$k];
	   $data['app_type']=$_POST['app_type'][$k];
	   $m->save($data);
	  //alert($m->getLastSQL());
	   //$list=$m->limit(1)->select();
	   //alert($_POST['luser'][$k]);
	   //$data['dq_id']=$_POST['dq_id'][$k];
	 }
	  //alert($m->getLastSQL());
	  $this->ajaxReturn('1');	 
  }
  

  //删除记录
  public function ajaxDeleteRecord() {
    $id = $_POST['id'];
    $m = M();
    $sql = "delete from a_law where id in($id)";
    $m->execute($sql);
    $this->ajaxReturn('',"成功",1);
  }
  
  public function ajaxChangeTypeRecords(){
    $id = $_POST["id"];
    $typeID = $_POST["type_id"];
    $type = $_POST["type"];
    $sql = "update a_law set $type=$typeID where id in ($id)";
    $m = M();
    $m->query($sql);
	$this->ajaxReturn('',"成功",1);
   // alert($_POST);
	/*$m=M('ALaw');
	if($m->setInc('status',"id in({$_POST['id']})"))
		$this->ajaxReturn('',"成功",1);
	else 	
	    $this->ajaxReturn('',"失败",0);*/
  }

  /*
  *执行审核
  */
  public function ajaxShenhe(){
    $id = $_POST["id"];
    //$typeID = $_POST["type_id"];
    //$type = $_POST["type"];
	$data['status'] = $_POST["status"];
    //$sql = "update a_law set $type=$typeID where id in ($id)";
    $m=M('ALaw');
 	if($m->where("id in({$_POST['id']})")->save($data)){
	  //alert($m->getLastSQL());
	  $this->ajaxReturn('',"审核完成",1);
	}
	else {	
	  //alert($m->getLastSQL());
	  $this->ajaxReturn('',"审核失败",0);
	}
	
  }


   /*
   *返回颁布法律部门
   */
   public function getGovAjax(){
	  $str='全国人大常委会,国务院,中华人民共和国国家发展和改革委员会,中华人民共和国科学技术部,中华人民共和国公安部,中华人民共和国监察部,中华人民共和国人力资源和社会保障部,中华人民共和国环境保护部,中华人民共和国交通运输部,中华人民共和国铁道部,中华人民共和国卫生部,国家质量监督检验检疫总局,国家安全生产监督管理总局,国家食品药品监督管理局,国家煤矿安全监察局,国家经济贸易委员会,国家标准化管理委员会,广东省安全生产监督局,广东省质量技术监督局'; 
	  $names=explode(',',$str);
	   $this->assign("govList",$names);
	   $this->display('govList');
   }


  private function _getHZRList($table) {
    $m = M();
    $rt = array();
    foreach ($table as $k => $v) {
      //if($v!='a_zy')
	    $list = $m->query("select * from $v");
	  //else 
	   // $list = $m->query("select * from $v where did!=0");
      $rt[$k] = $this->_reList(array(),$list,0);
    }
    return $rt;
  }

  private function _reList($rt,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $rt[$k] = array(id=>$v["id"],title=>$v["title"],law_count=>$v['law_count'],dwon_line_ids=>array(),downLine=>array());
        $rt[$k]["downLine"] = $this->_reList(array(),$list,$v['id']);
        foreach ($rt[$k]["downLine"] as $key => $value) {
          $rt[$k]["dwon_line_ids"][] = $value['id'];
        }
      }
    }
    return $rt;
  }

  public function ajaxChangeSelType() {
    $type = $_POST['type'];
    $o = $this->getTypeTwo($type);
    $this->ajaxReturn($o,"成功",1);
  }
  
  

  //params  type:   hy_id,zy_id,dq_id,lawtype_id
  public function getTypeTwo($type) {
    $obj = array(
      hy_id =>array(table => "a_hy",select => "id,title"),
      zy_id =>array(table => "a_zy",select => "id,title"),
	  app =>array(table => "a_law_apptype",select => "id,name"),
      dq_id =>array(table => "a_region",select => "id,title"),
    );
    $m = M();
    if ($type == "lawtype_id" || $type == "app") {
      if($type == "lawtype_id")
	    $sql = "select id,Laytype_name as title from a_lawtype";
	   else
	     $sql = "select id,name as title from a_law_apptype";
      $rt = $m->query($sql);
    }else {
      $rt = $this->_getHZRList(array($obj[$type]['table']));
      $rt = $rt[0];
    }
    $o["list"] = $rt;
    $o["type_id"] = $type;
    return $o;
  }

  
  /*
  * 执行文件上传
  * @_FILES
  */
  private function _doUpload($file){
	  //$fileSize = $_FILES['file']['size'];	
	  import("ORG.Net.UploadFile");
	  $upload = new UploadFile(); // 实例化上传类
	  $upload->maxSize  = 10048576 ; // 设置附件上传大10小1M
	  $upload->subType = date;
	  $upload->saveRule=com_create_guid; 
	  $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg','doc','docx','xls','xlsx','rar','zip','pdf','txt'); // 设置附件上传类型
	  $upload->savePath =  './attachments/law/'; // 设置附件上传目录
	  if(!$upload->upload()) { // 上传错误提示错误信息
		$this->error($upload->getErrorMsg());
		eixt();
	  }
	  return $upload->getUploadFileInfo();
  }
  
}
?>